//
//  Segment.swift
//  LiuheCommunity
//
//  Created by 罗恒 on 2018/1/18.
//  Copyright © 2018年 luo. All rights reserved.
//

import UIKit

let w:CGFloat = UIScreen.main.bounds.size.width
let h:CGFloat = UIScreen.main.bounds.size.height

protocol SelectSegmentDelegate:NSObjectProtocol {
    func selectSeg(index:Int)
}

class Segment: UIView {

    var delegate: SelectSegmentDelegate?
    var selectBtn:UIButton?//选中的btn
//    var slider:UILabel?//标题
    
    func setSegmentView(arr : [String]) -> UIView {
        
        let segment_width:Int = (Int(w)-arr.count-1)/arr.count
        
        for str:String in arr {
            let count:Int =  arr.index(of: str)!
            
            let btn = UIButton.init(frame: CGRect.init(x: segment_width*count+count+1, y: 0, width: segment_width, height: 40))
            btn.setTitle(str, for: .normal)
            btn.setTitleColor(UIColor.gray, for: .normal)
            btn.setTitleColor(UIColor.brown, for: .selected)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
            btn.addTarget(self, action: #selector(buttonClick(sender:)), for: .touchUpInside)
            btn.tag = count
            self.addSubview(btn)
            
            if count == 0 {
                btn.isSelected = true
                selectBtn = btn
            }
//            let ima = UIImageView.init(image: UIImage.init(named: "v_line1.png"))
//            ima.frame = CGRect.init(x: segment_width*count+count, y: 0, width: 1, height: 36)
//            ima.contentMode = .left
//            self.addSubview(ima)
        }
        
        let ima1 = UIImageView.init(image: UIImage.init(named: "h_line1.png"))
        ima1.backgroundColor = UIColor.gray
        ima1.frame = CGRect.init(x: 0, y: 40, width: w, height: 1)
        ima1.contentMode = .bottom
        self.addSubview(ima1)

//        slider = UILabel.init(frame: CGRect.init(x: 1+segment_width/2-30, y: 30, width: 60, height: 4))
//        slider?.backgroundColor = UIColor.green
//        self.addSubview(slider!)
        
        return self
    }
    
    
    @objc func buttonClick(sender:UIButton) -> Void {
        selectBtn?.isSelected = false
        sender.isSelected = true
        selectBtn = sender
        UIView.animate(withDuration: 0.5) {
            _ = sender.frame.size.width/2+1 + (sender.frame.size.width+1)*CGFloat(sender.tag)
//            self.slider?.frame.origin.x = CGFloat(x)-30
        }
        
        delegate?.selectSeg(index: sender.tag)
    }
    
    
    
    
    
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
